package com.ulook.lookplanet.ui.notifications;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ulook.lookplanet.base.BaseViewModel2;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.data.repository.NotificationsRepository;

import java.util.HashMap;
import java.util.List;

public class NotificationsViewModel extends BaseViewModel2 {

    private NotificationsRepository repository;
    private TUser currUser;
    private final HashMap<Integer, VMsgUser> userMsgMap = new HashMap<>();

    public NotificationsViewModel(){
        repository = NotificationsRepository.getInstance();
    }

    public TUser getCurrUser() {
        return currUser;
    }
    public void setCurrUser(TUser currUser) {
        this.currUser = currUser;
    }
    public HashMap getUserMsgMap(){
        return userMsgMap;
    }


    /**
     * 获取用户聊天列表
     */
    public HashMap getChatList(){
        List<VMsgUser> msgUsers = repository.getChatList(currUser.getId());
        for(int i = 0; i < msgUsers.size(); i++){
            int fromUserId = msgUsers.get(i).getFromuser();
            int toUserId = msgUsers.get(i).getTouser();
            // 对方发出的
            if(fromUserId != currUser.getId()){
                if(!userMsgMap.containsKey(fromUserId)){
                    userMsgMap.put(fromUserId, getLatestMsg(fromUserId, toUserId));
                }
            //我发出的
            }else {
                if(!userMsgMap.containsKey(toUserId)){
                    VMsgUser last = getLatestMsg(fromUserId, toUserId);
                    // 交换from和to的内容
                    int id = last.getFromuser();
                    String name = last.getFromname();
                    String head = last.getFromheadimg();
                    last.setFromuser(last.getTouser());
                    last.setFromname(last.getToname());
                    last.setFromheadimg(last.getToheadimg());
                    last.setTouser(id);
                    last.setToname(name);
                    last.setToheadimg(head);
                    userMsgMap.put(toUserId, last);
                }
            }

        }
        return userMsgMap;
    }

    /**
     * 获取聊天最新一条消息
     */
    public VMsgUser getLatestMsg(int fromUserId, int toUserId){
        return repository.getLatestMsg(fromUserId, toUserId);
    }

    /**
     * 获取未读消息数量
     */
    public int getUnreadNum(int fromUserId){
        return repository.getUnreadNum(fromUserId);
    }
}